<template>
  <div ref="graphContainer" style="width:100%;height:420px;"></div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  name: 'MindmapGraph',
  props: {
    mindmap: { type: Object, required: true },
    theme: { type: String, default: 'auto' },
    activeNode: { type: Object, default: null },
    dimension: { type: String, default: '' },
  },
  data() {
    return { chart: null };
  },
  watch: {
    mindmap: {
      handler() { this.renderGraph(); },
      deep: true
    },
    activeNode() { this.renderGraph(); }
  },
  mounted() {
    this.renderGraph();
    window.addEventListener('resize', this.resize);
  },
  beforeUnmount() {
    if (this.chart && !this.chart.isDisposed()) {
      try {
        this.chart.dispose();
      } catch (error) {
        console.warn('MindmapGraph图表销毁时出现警告:', error);
      }
    }
    window.removeEventListener('resize', this.resize);
  },
  methods: {
    resize() {
      if (this.chart && !this.chart.isDisposed()) {
        this.$nextTick(() => {
          this.chart.resize();
        });
      }
    },
    renderGraph() {
      if (!this.mindmap || !this.mindmap.title) return;
      try {
        if (!this.chart) {
          this.chart = echarts.init(this.$refs.graphContainer);
        } else if (this.chart.isDisposed()) {
          this.chart = echarts.init(this.$refs.graphContainer);
        }
      } catch (error) {
        console.error('初始化图表失败:', error);
        return;
      }
      // 递归转换为graph节点和边
      const nodes = [];
      const links = [];
      let idx = 0;
      // 维度样式参数
      let layout = 'force';
      let colorFn = (level, node) => level === 0 ? '#00ffe7' : level === 1 ? '#22d3ee' : level === 2 ? '#06b6d4' : '#0891b2';
      let edgeColorFn = (level) => level === 0 ? '#00ffe7' : level === 1 ? '#22d3ee' : '#00bcd4';
      let labelColorFn = (level) => level === 0 ? '#ffffff' : level === 1 ? '#1a202c' : '#2d3748';
      let themeBranchColors = ['#ffb300', '#00e676', '#ff4081', '#7c4dff', '#00bcd4', '#ff5252', '#ffd600', '#536dfe', '#69f0ae'];
      if (this.dimension === 'time') {
        layout = 'circular';
        colorFn = (level, node) => level === 0 ? '#00ffe7' : '#22d3ee';
        edgeColorFn = () => '#00bcd4';
        labelColorFn = () => '#0073e6';
      } else if (this.dimension === 'space') {
        layout = 'force';
        colorFn = (level, node) => node.regionColor || ['#00bcd4', '#ffb300', '#7c4dff', '#00e676'][level % 4];
        edgeColorFn = () => '#536dfe';
        labelColorFn = () => '#0097a7';
      } else if (this.dimension === 'theme') {
        layout = 'force';
        colorFn = (level, node) => themeBranchColors[node.themeIdx % themeBranchColors.length] || '#00ffe7';
        edgeColorFn = () => '#ff4081';
        labelColorFn = () => '#ff4081';
      }
      const dimension = this.dimension;
      function traverse(node, parentId = null, level = 0, branchIdx = 0) {
        const id = 'n' + (idx++);
        const baseSize = 60; // 减小基础节点大小从80到60
        // 根据层级调整节点大小，第三层稍小一些
        const nodeSize = Math.max(baseSize - level * 10, 25); // 减小最小节点大小从35到25
        let displayName = node.title || '未命名节点';
        // 根据层级优化节点文本显示
        const maxDisplayLength = level === 0 ? 12 : (level === 1 ? 10 : 8);
        if (displayName.length > maxDisplayLength) {
          displayName = displayName.substring(0, maxDisplayLength) + '...';
        }
        // 移除冗余符号
        displayName = displayName.replace(/[（）()【】\[\]]/g, '');
        
        // 主题维度分支色标
        let themeIdx = branchIdx;
        nodes.push({
          id,
          name: displayName,
          symbolSize: nodeSize,
          itemStyle: {
            color: colorFn(level, { ...node, themeIdx }),
            borderColor: '#fff',
            borderWidth: 2,
            shadowBlur: level === 0 ? 12 : 8, // 减小节点阴影从16到12/8
            shadowColor: colorFn(level, { ...node, themeIdx }),
            opacity: 1
          },
          label: {
            show: true,
            color: labelColorFn(level),
            fontWeight: level === 0 ? 'bold' : 'normal',
            fontSize: Math.max(11 - level * 1, 7), // 减小字体大小，从13开始到11开始
            backgroundColor: level === 0 ? 'rgba(255,255,255,0.95)' : 'rgba(255,255,255,0.85)',
            borderRadius: 4, // 减小圆角从6到4
            padding: level === 0 ? [4, 8] : [3, 6], // 减小内边距
            shadowColor: colorFn(level, { ...node, themeIdx }),
            shadowBlur: level === 0 ? 8 : 4, // 减小阴影模糊从10和6到8和4
            textBorderColor: 'transparent',
            textBorderWidth: 0,
            overflow: 'truncate',
            borderColor: colorFn(level, { ...node, themeIdx }),
            borderWidth: level === 0 ? 2 : 1
          },
          draggable: true,
        });
        if (parentId) {
          links.push({ 
            source: parentId, 
            target: id, 
            lineStyle: { 
              color: edgeColorFn(level), 
              width: Math.max(3 - level * 0.5, 1),
              curveness: 0.2,
              opacity: 0.8,
              shadowColor: edgeColorFn(level),
              shadowBlur: 3
            } 
          });
        }
        if (Array.isArray(node.children)) {
          node.children.forEach((child, idx) => {
            if (typeof child === 'object') traverse(child, id, level + 1, dimension === 'theme' && level === 1 ? idx : branchIdx);
          });
        }
      }
      traverse.call(this, this.mindmap);
      this.chart.setOption({
        backgroundColor: 'transparent',
        animationDuration: 1200,
        toolbox: {
          show: true,
          feature: {
            restore: { title: '还原' },
            saveAsImage: { title: '保存为图片' }
          },
          iconStyle: {
            borderColor: '#00f5ff'
          },
          emphasis: {
            iconStyle: {
              borderColor: '#00ffe7'
            }
          }
        },
        series: [{
          type: 'graph',
          layout,
          roam: true, // 启用缩放和拖拽
          draggable: true,
          symbol: 'circle',
          data: nodes,
          links: links,
          edgeSymbol: ['none', 'arrow'],
          edgeSymbolSize: [4, 10],
          force: {
            repulsion: layout === 'force' ? 1000 : 600, // 进一步增加斥力，适应3层结构
            edgeLength: layout === 'force' ? 220 : 150, // 增加边长，为3层结构提供更多空间
            gravity: 0.05, // 稍微减少引力，让节点分布更均匀
            layoutAnimation: true,
            friction: 0.85 // 增加摩擦力，减少震荡
          },
          lineStyle: {
            color: '#00f5ff',
            width: 2,
            curveness: 0.3,
            shadowColor: '#00f5ff',
            shadowBlur: 8
          },
          label: {
            show: true,
            position: 'inside',
            fontWeight: 'bold',
            color: '#232b3b',
            fontSize: 12,
            overflow: 'break',
            width: 60,
            lineHeight: 14
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: { 
              width: 6, 
              color: '#00ffe7',
              shadowBlur: 10,
              shadowColor: '#00ffe7'
            },
            itemStyle: { 
              borderColor: '#00ffe7', 
              borderWidth: 4,
              shadowBlur: 20,
              shadowColor: '#00ffe7'
            }
          },
          animation: true
        }]
      });
    }
  }
}
</script>
